﻿//========================================================= 
/**@file LC_CommandDriver.h
 * @brief LC基于命令操作方式的驱动
 * 
 * @date 2016-04-02   14:48:29
 * @author Zhyioo 
 * @version 1.0
 */ 
//--------------------------------------------------------- 
#ifndef _LIBZHOUYB_COMMANDDRIVER_H_
#define _LIBZHOUYB_COMMANDDRIVER_H_
//--------------------------------------------------------- 
#include "../../include/Base.h"
#include "../../include/Extension.h"
#include "../../include/Container.h"
//--------------------------------------------------------- 
/// 根据指定的对象生成一个命令
#define _MakeObjCMD(obj, cls, funcName) Command::Make((obj), &cls::funcName, #cls"::"#funcName)
/// 在类中创建一个自己的命令
#define _MakeCMD(cls, funcName) _MakeObjCMD(*this, cls, funcName)
/// 根据指定的类创建一个命令
#define _MakeTCMD(cls, funcName) Command::Make<cls>(#cls"::"##funcName)
/// 创建一个类静态的函数
#define _MakeCMDF(cls, funcName) Command::MakeF(&(cls::funcName), #cls"::"#funcName)
/// 创建一个C方式的函数
#define _MakeF(funcName) Command::MakeF(funcName, #funcName)
/// 在类中注册自己的函数,并绑定一个参数
#define _RegisteArgCMD(cls, funcName, arg) (this->_Registe(#funcName, _MakeCMD(cls, funcName), arg))
/// 类中注册自己的函数
#define _RegisteCMD(cls, funcName) (this->_Registe(#funcName, _MakeCMD(cls, funcName)))
/// 类中命令函数定义
#define LC_CMD_METHOD(methodName) bool methodName(ICommandHandler::Arguments& arg, ICommandHandler::Arguments& rlt)
//--------------------------------------------------------- 
namespace zhou_yb {
namespace application {
namespace driver {
//--------------------------------------------------------- 
/// Command接口
struct ICommandHandler
{
    /// 命令解析器类型
    typedef IStringArguments Arguments;
    /// 执行命令
    virtual bool OnCommand(Arguments&, Arguments&) = 0;
    /// 命令是否有效
    virtual bool IsRunable() const = 0;

    virtual ~ICommandHandler() {}
};
//--------------------------------------------------------- 
/// 类成员函数的命令形式
template<class T>
class CommandHandler : public ICommandHandler
{
public:
    typedef bool(T::*fpOnCommand)(ICommandHandler::Arguments&, ICommandHandler::Arguments&);
protected:
    Ref<T> _pObj;
    fpOnCommand _fpOnCommand;

    bool _IsNull() const
    {
        return _pObj.IsNull() || _fpOnCommand == NULL;
    }
public:
    CommandHandler(T& obj, const fpOnCommand cmdHandle)
    {
        _pObj = Ref<T>(obj);
        _fpOnCommand = cmdHandle;
    }
    virtual bool OnCommand(ICommandHandler::Arguments& arg, ICommandHandler::Arguments& rlt)
    {
        if(_IsNull())
            return false;
        return ((*_pObj).*_fpOnCommand)(arg, rlt);
    }
    virtual bool IsRunable() const
    {
        return !_IsNull();
    }
};
/// C全局函数的命令方式
template<>
class CommandHandler<void> : public ICommandHandler
{
public:
    typedef bool(*fpOnCommand)(ICommandHandler::Arguments&, ICommandHandler::Arguments&);
protected:
    fpOnCommand _fpOnCommand;
public:
    CommandHandler(const fpOnCommand cmdHandle)
    {
        _fpOnCommand = cmdHandle;
    }
    virtual bool OnCommand(ICommandHandler::Arguments& arg, ICommandHandler::Arguments& rlt)
    {
        if(!IsRunable())
            return false;
        return _fpOnCommand(arg, rlt);
    }
    virtual bool IsRunable() const
    {
        return _fpOnCommand != NULL;
    }
};
//--------------------------------------------------------- 
/// 可运行的命令
struct ICommand : public ICommandHandler, public LoggerBehavior
{
    /// 返回命令名称
    virtual const char* Name() const = 0;
    /// 输出命令信息
    LOGGER(virtual void Print(LoggerAdapter& _log, size_t lv) {})
};
//--------------------------------------------------------- 
/// 基本命令(用于绑定封装类中的命令函数)
class Command : public ICommand, public RefObject
{
protected:
    //----------------------------------------------------- 
    static list_t<Command> _Cmds;

    shared_obj<ICommandHandler*> _handle;
    string _name;

    Command()
    {
        _handle.obj() = NULL;
    }
    //----------------------------------------------------- 
public:
    //----------------------------------------------------- 
    template<class T>
    static Ref<Command> Make(T& obj, const typename CommandHandler<T>::fpOnCommand cmdHandler, const char* name = NULL)
    {
        Command cmd;
        cmd._name = _strput(name);
        cmd._handle = new CommandHandler<T>(obj, cmdHandler);
        Command::_Cmds.push_back(cmd);
        return Command::_Cmds.back();
    }
    template<class TCommand>
    static Ref<TCommand> Make(const char* name = NULL)
    {
        Command cmd;
        TCommand* pCmd = new TCommand();
        ICommandHandler* pHandler = pCmd;
        cmd._name = _strput(name);
        cmd._handle = pHandler;
        Command::_Cmds.push_back(cmd);
        return (*pCmd);
    }
    template<class TCommand>
    static Ref<Command> Make(Ref<TCommand>& cmd, const char* name = NULL)
    {
        cmd = Make<TCommand>(name);
        return Command::_Cmds.back();
    }
    static Ref<Command> MakeF(const CommandHandler<void>::fpOnCommand cmdHandler, const char* name = NULL)
    {
        Command cmd;
        cmd._name = _strput(name);
        cmd._handle = new CommandHandler<void>(cmdHandler);
        Command::_Cmds.push_back(cmd);
        return Command::_Cmds.back();
    }
    //----------------------------------------------------- 
    static size_t CleanUp()
    {
        list_t<Command>::iterator itr;
        size_t count = 0;
        for(itr = _Cmds.begin();itr != _Cmds.end(); ++itr)
        {
            if(!itr->IsRunable())
            {
                itr = list_helper<Command>::erase(_Cmds, itr);
                ++count;
            }
        }
        return count;
    }
    //----------------------------------------------------- 
    virtual ~Command()
    {
        // 最后一个对象
        if(_handle.ref_count() < 2)
        {
            delete _handle.obj();
            _handle.obj() = NULL;

            list_helper<Command>::remove(Command::_Cmds, (*this));
        }
    }
    virtual const char* Name() const
    {
        return _name.c_str();
    }
    virtual bool OnCommand(ICommandHandler::Arguments& arg, ICommandHandler::Arguments& rlt)
    {
        // 对象已失效
        if(_handle.obj() == NULL)
            return false;
        return _handle.obj()->OnCommand(arg, rlt);
    }
    virtual bool IsRunable() const
    {
        return _handle.obj() != NULL && _handle.obj()->IsRunable();
    }
    //----------------------------------------------------- 
    inline virtual ICommandHandler* Handle() const
    {
        return _handle.obj();
    }
    bool operator==(const Command& obj)
    {
        return _handle == obj._handle;
    }
    bool operator!=(const Command& obj)
    {
        return !(operator==(obj));
    }
    //----------------------------------------------------- 
    /// 输出命令信息
    LOGGER(virtual void Print(LoggerAdapter& _log, size_t lv = 0)
    {
        const char FLAG = '|';
        const char HEAD = '+';
        const char NODE = '-';
        string title;
        string print_tab;
        if(lv > 0)
        {
            title = _tree(lv - 1, FLAG);
            title += _tree_node(1, HEAD, NODE);
            print_tab = _tree(lv + 1, FLAG);
        }
        else
        {
            print_tab = _tree_node(1, '`', NODE);
        }
        _log << title << "Command:<" << Name() << ">\n";
        _log << print_tab << "Address:<" << _hex_num(Handle()) << ">\n";
    })
    //----------------------------------------------------- 
};
//--------------------------------------------------------- 
/// 复合命令
class ComplexCommand : public ICommand, public RefObject
{
public:
    //----------------------------------------------------- 
    typedef uint CommandOption;
    /// 命令执行选项
    enum RunOption
    {
        /// 上一个命令成功时执行
        RunOnSuccess = 0x00,
        /// 上一个命令失败时执行
        RunOnFailed =  0x01,
        /// 任何时候都执行命令,并且忽略该命令的执行结果
        RunOnAlways =  0x02,
        /// 执行完该命令后不再继续执行后续的命令
        RunOnEOF =     0x03,
    };
    /// 命令绑定的参数选项
    enum BindOption
    {
        /// 只使用绑定的参数
        BindOnly = 0x00,
        /// 将原始参数导入到绑定的参数中,不做输出
        BindImport = 0x04,
        /// 将绑定的参数添加到原始的参数中,可作为输出
        BindExport = 0x08
    };
    /// 判断是否为执行选项
    inline static bool IsRunOption(CommandOption option, uint flag)
    {
        return (option & 0x03) == flag;
    }
    /// 判断是否为绑定选项
    inline static bool IsBindOption(CommandOption option, uint flag)
    {
        return (option & 0x0C) == flag;
    }
    /// 将字符串格式的命令选项转换为对应的枚举类型
    static CommandOption StringToOption(const ByteArray& sOption)
    {
        RunOption runOption = static_cast<RunOption>(0x00);
        if(StringConvert::Contains(sOption, "RunOnSuccess", true))
            runOption = RunOnSuccess;
        else if(StringConvert::Contains(sOption, "RunOnFailed", true))
            runOption = RunOnFailed;
        else if(StringConvert::Contains(sOption, "RunOnAlways", true))
            runOption = RunOnAlways;
        else if(StringConvert::Contains(sOption, "RunOnEOF", true))
            runOption = RunOnEOF;

        BindOption bindOption = static_cast<BindOption>(0x00);
        if(StringConvert::Contains(sOption, "BindOnly", true))
            bindOption = BindOnly;
        else if(StringConvert::Contains(sOption, "BindImport", true))
            bindOption = BindImport;
        else if(StringConvert::Contains(sOption, "BindExport", true))
            bindOption = BindExport;
        return static_cast<CommandOption>(runOption | bindOption);
    }
    /// 将命名运行方式的枚举类型转换为字符串描述
    static string OptionToString(CommandOption option)
    {
        string sOption = "";
        if(IsRunOption(option, RunOnFailed))
        {
            sOption += "RunOnFailed";
        }
        else if(IsRunOption(option, RunOnAlways))
        {
            sOption += "RunOnAlways";
        }
        else if(IsRunOption(option, RunOnEOF))
        {
            sOption += "RunOnEOF";
        }
        else
        {
            sOption += "RunOnSuccess";
        }
        sOption += "|";

        if(IsBindOption(option, BindImport))
        {
            sOption += "BindImport";
        }
        else if(IsBindOption(option, BindExport))
        {
            sOption += "BindExport";
        }
        else
        {
            sOption += "BindOnly";
        }
        return sOption;
    }
    //----------------------------------------------------- 
protected:
    /// 命令结构
    struct CommandNode
    {
        Ref<ICommand> Cmd;
        bool IsBind;
        StringArguments Argument;
        CommandOption Option;
    };
    /// 命令名称
    string _name;
    /// 命令
    list_t<CommandNode> _cmds;
    /// 生成新的命令
    CommandNode& _MakeCmd(bool isPrefixCmd)
    {
        list_t<CommandNode>::iterator itr = (isPrefixCmd ? _cmds.push_front() : _cmds.push_back());
        return (*itr);
    }
    /// 设置属性
    inline ComplexCommand& _Bind(Ref<ICommand> cmd, CommandOption option, bool isPrefixCmd)
    {
        if(cmd == (*this))
            return (*this);
        CommandNode& node = _MakeCmd(isPrefixCmd);
        node.IsBind = false;
        node.Cmd = cmd;
        node.Option = option;
        return (*this);
    }
    /// 设置属性
    ComplexCommand& _Bind(Ref<ICommand> cmd, CommandOption option, const IStringArguments& arg, bool isPrefixCmd)
    {
        if(cmd == (*this))
            return (*this);
        CommandNode& node = _MakeCmd(isPrefixCmd);
        StringArguments::CopyTo(arg, node.Argument);
        node.IsBind = true;
        node.Cmd = cmd;
        node.Option = option;
        return (*this);
    }
    /// 设置属性
    ComplexCommand& _Bind(Ref<ICommand> cmd, CommandOption option, IStringArgParser& parser, const char* sArg, bool isPrefixCmd)
    {
        if(cmd == (*this))
            return (*this);
        CommandNode& node = _MakeCmd(isPrefixCmd);
        node.IsBind = (sArg != NULL);
        if(node.IsBind)
        {
            parser.Parse(sArg, node.Argument);
        }
        node.Cmd = cmd;
        node.Option = option;
        return (*this);
    }
    //----------------------------------------------------- 
public:
    //----------------------------------------------------- 
    ComplexCommand() { _name = ""; }
    virtual ~ComplexCommand()
    {
        _cmds.clear();
    }
    //----------------------------------------------------- 
    /// 绑定基本命令到该组中(前置)
    inline ComplexCommand& PrefixBind(Ref<ICommand> cmd, const IStringArguments& bindArg, CommandOption option = ComplexCommand::RunOnSuccess)
    {
        return _Bind(cmd, option, bindArg, true);
    }
    /// 绑定基本命令到该组中(前置)
    inline ComplexCommand& PrefixBind(Ref<ICommand> cmd, IStringArgParser& parser, const char* sArg, CommandOption option = ComplexCommand::RunOnSuccess)
    {
        return _Bind(cmd, option, parser, sArg, true);
    }
    /// 绑定复合命令到该组中(前置)
    inline ComplexCommand& PrefixBind(Ref<ICommand> cmd, CommandOption option = ComplexCommand::RunOnSuccess)
    {
        return _Bind(cmd, option, true);
    }
    /// 绑定基本命令到该组中(后置)
    inline ComplexCommand& Bind(Ref<ICommand> cmd, const IStringArguments& bindArg, CommandOption option = ComplexCommand::RunOnSuccess)
    {
        return _Bind(cmd, option, bindArg, false);
    }
    /// 绑定基本命令到该组中(后置)
    inline ComplexCommand& Bind(Ref<ICommand> cmd, IStringArgParser& parser, const char* sArg, CommandOption option = ComplexCommand::RunOnSuccess)
    {
        return _Bind(cmd, option, parser, sArg, false);
    }
    /// 绑定基本命令到该组中(后置)
    inline ComplexCommand& Bind(Ref<ICommand> cmd, CommandOption option = ComplexCommand::RunOnSuccess)
    {
        return _Bind(cmd, option, false);
    }
    /// 返回命令名称
    virtual const char* Name() const
    {
        return _name.c_str();
    }
    /// 命令一直有效
    virtual bool IsRunable() const { return true; }
    /// 运行命令(支持使用绑定的数据参数)
    virtual bool OnCommand(ICommandHandler::Arguments& arg, ICommandHandler::Arguments& rlt)
    {
        LOG_FUNC_NAME();
        LOGGER(_log << "RunCommand:<" << Name() << "," << _hex_num(this) << ">\n");
        list_t<CommandNode>::iterator itr;
        bool bCommand = true;
        for(itr = _cmds.begin();itr != _cmds.end(); ++itr)
        {
            if(itr->Cmd.IsNull())
            {
                LOGGER(_log.WriteLine("Null Command"));
                continue;
            }
            LOGGER(_log << "OnCommand:<" << itr->Cmd->Name() << ">\n");
            LOGGER(_log << " IsRunable:<" << itr->Cmd->IsRunable() << ">\n");
            LOGGER(_log << " Option:<" << OptionToString(itr->Option) << ">\n");

            // 上次执行失败
            if(!bCommand)
            {
                if(IsRunOption(itr->Option, RunOnSuccess) || IsRunOption(itr->Option, RunOnEOF))
                {
                    LOGGER(_log.WriteLine("RunOnSuccess Skipped"));
                    continue;
                }
            }
            if(bCommand && IsRunOption(itr->Option, RunOnFailed))
            {
                LOGGER(_log.WriteLine("RunOnFailed Skipped"));
                continue;
            }

            bool bSubCommand = true;
            ICommandHandler::Arguments* pArg = &arg;
            StringArguments bindArg;
            LOGGER(_log << "IsBind:<" << itr->IsBind << ">\n");
            if(itr->IsBind)
            {
                // 需要使用外部导入的参数 
                if(IsBindOption(itr->Option, BindImport))
                {
                    StringArguments::CopyTo(arg, bindArg);
                    StringArguments::CopyTo(itr->Argument, bindArg);
                    pArg = &bindArg;
                }
                else if(IsBindOption(itr->Option, BindExport))
                {
                    StringArguments::CopyTo(itr->Argument, arg);
                }
                else
                {
                    StringArguments::CopyTo(itr->Argument, bindArg);
                    pArg = &bindArg;
                }
            }
            LOGGER(_log << "Arguments:[" << pArg->Count() << "]\n";
            size_t width = 0;
            IStringArguments::EnumeratorType enumer = pArg->GetEnumerator();
            while(enumer.MoveNext())
            {
                width = _max(enumer.Current().Key.length(), width);
                _log << " -> " << _left_width(enumer.Current().Key, width) << " : <" << enumer.Current().Value << ">\n";
            });

            bSubCommand = itr->Cmd->OnCommand(*pArg, rlt);
            LOGGER(_log << "CommandResult:<" << bSubCommand << ">\n");

            LOGGER(_log << "Result:[" << rlt.Count() << "]\n";
            enumer = rlt.GetEnumerator();
            while(enumer.MoveNext())
            {
                width = _max(enumer.Current().Key.length(), width);
                _log << " => " << _left_width(enumer.Current().Key, width) << " : <" << enumer.Current().Value << ">\n";
            });
            if(!IsRunOption(itr->Option, RunOnAlways))
                bCommand = bSubCommand;
            LOGGER(_log << "CommandStatus:<" << bCommand << ">\n");
            LOGGER(_log.WriteLine("/=------------"));
            // 最后一个命令
            if(IsRunOption(itr->Option, RunOnEOF))
                break;
        }
        LOGGER(_log << "EndCommand:<" << Name() << ">\n");
        return _logRetValue(bCommand);
    }
    //----------------------------------------------------- 
    /// 解绑指定名称的命令
    bool UnBind(const char* name, bool isIgnoreCase = true)
    {
        list_t<CommandNode>::iterator itr;
        ByteArray srcName(name);
        ByteArray dstName;
        bool bFind = false;
        for(itr = _cmds.begin();itr != _cmds.end(); ++itr)
        {
            if(itr->Cmd.IsNull())
                continue;
            
            dstName = itr->Cmd->Name();
            if(StringConvert::Contains(dstName, srcName, isIgnoreCase))
            {
                _cmds.erase(itr);
                bFind = true;
                break;
            }
        }
        return bFind;
    }
    /// 设置名称
    inline void SetName(const char* name)
    {
        _name = _strput(name);
    }
    /// 清空所有子命令
    inline void Clear()
    {
        _cmds.clear();
    }
    /// 返回子命令的数目
    inline size_t Count() const
    {
        return _cmds.size();
    }
    /// 拆分命令
    size_t Split(list_t<ComplexCommand> & items)
    {
        list_t<CommandNode>::iterator itr;
        size_t count = 0;
        for(itr = _cmds.begin();itr != _cmds.end(); ++itr)
        {
            if(!(itr->Cmd.IsNull()))
            {
                items.push_back();
                items.back()._name = itr->Cmd->Name();
                items.back().Bind(itr->Cmd);
                ++count;
            }
        }
        return count;
    }
    //----------------------------------------------------- 
    LOGGER(virtual void SelectLogger(const LoggerAdapter& llog)
    {
        LoggerBehavior::SelectLogger(llog);
        list_t<CommandNode>::iterator itr;
        for(itr = _cmds.begin();itr != _cmds.end(); ++itr)
        {
            if(!itr->Cmd.IsNull())
            {
                itr->Cmd->SelectLogger(llog);
            }
        }
    }
    virtual void ReleaseLogger(const LoggerAdapter* plog = NULL)
    {
        LoggerBehavior::ReleaseLogger(plog);
        list_t<CommandNode>::iterator itr;
        for(itr = _cmds.begin();itr != _cmds.end(); ++itr)
        {
            if(!itr->Cmd.IsNull())
            {
                itr->Cmd->ReleaseLogger(plog);
            }
        }
    })
    /// 输出命令信息
    LOGGER(virtual void Print(LoggerAdapter& _log, size_t lv = 0)
    {
        const char FLAG = '|';
        const char HEAD = '+';
        const char NODE = '-';
        string title;
        if(lv > 0)
        {
            title += _tree(lv - 1, FLAG);
            title += _tree_node(1, HEAD, NODE);
        }
        string sub_title = _tree(lv, FLAG);
        sub_title += _tree_node(1, HEAD, NODE);

        _log << title << "ComplexCommand:<" << Name() << ">\n";
        ++lv;

        string print_tab = _tree(lv, FLAG);
        string print_sub_tab = print_tab;
        print_sub_tab += _tree(1, FLAG);

        if(lv > 10)
        {
            _log << print_tab << "Too Much Lv, Error Command, Please Check Command..." << endl;
            return ;
        }

        list_t<CommandNode>::iterator itr;
        size_t index = 0;
        size_t lastIndex = _cmds.size();
        IStringArguments::EnumeratorType enumer;
        size_t width = 0;
        size_t count = 0;
        string displayMsg;
        for(itr = _cmds.begin();itr != _cmds.end(); ++itr)
        {
            ++index;
            if(!(itr->Cmd.IsNull()))
            {
                itr->Cmd->Print(_log, lv);
            }
            else
            {
                _log << sub_title << "Command:<Null>" << endl;
            }
            if(itr->IsBind)
            {
                _log << print_tab << "Argument:<" << itr->Argument.Count() << ">\n";
                width = 0;
                count = 0;
                enumer = itr->Argument.GetEnumerator();
                while(enumer.MoveNext())
                {
                    ++count;
                    displayMsg = "\"";
                    displayMsg += enumer.Current().Key;
                    displayMsg += "\"";

                    width = _max(displayMsg.length(), width);
                    _log << print_sub_tab;
                    _log << _left_width(displayMsg, width) << " : \"" << enumer.Current().Value << "\"\n";
                }
            }
            if(index == lastIndex && lv == 1)
            {
                _log << _tree_node(1, '`', NODE);
            }
            else
            {
                _log << print_tab;
            }
            _log << "Option:<" << OptionToString(itr->Option) << ">\n";
        }
    })
    //----------------------------------------------------- 
};
//--------------------------------------------------------- 
/// 命令集合
class CommandCollection : public RefObject
{
protected:
    //----------------------------------------------------- 
    /// 命令集合
    list_t<ComplexCommand> _cmd_collection;
    /// 生成一个新的命令
    Ref<ComplexCommand> _NewCommand(const ByteArray& name)
    {
        _cmd_collection.push_back();

        ByteBuilder tmp(8);
        tmp = name;
        _cmd_collection.back().SetName(tmp.GetString());
        return _cmd_collection.back();
    }
    /// 注册自己的内部命令
    Ref<ComplexCommand> _Registe(const ByteArray& cmdName, Ref<ICommand> cmd)
    {
        Ref<ComplexCommand> complexCmd = Registe(cmdName.GetString());
        // 第一个命令总是RunOnSuccess
        complexCmd->Bind(cmd);
        return complexCmd;
    }
    /// 注册自己的内部命令
    Ref<ComplexCommand> _Registe(const ByteArray& cmdName, Ref<ICommand> cmd, const IStringArguments& bindArg)
    {
        Ref<ComplexCommand> complexCmd = Registe(cmdName.GetString());
        // 第一个命令总是RunOnSuccess
        complexCmd->Bind(cmd, bindArg);
        return complexCmd;
    }
    list_t<ComplexCommand>::iterator _Find(const ByteArray& cmdName, bool isIgnoreCase)
    {
        list_t<ComplexCommand>::iterator itr;
        for(itr = _cmd_collection.begin();itr != _cmd_collection.end(); ++itr)
        {
            if(StringConvert::Compare(itr->Name(), cmdName, isIgnoreCase))
            {
                return itr;
            }
        }
        return _cmd_collection.end();
    }
    inline bool _IsEof(list_t<ComplexCommand>::iterator itr)
    {
        return itr == _cmd_collection.end();
    }
    //----------------------------------------------------- 
public:
    //----------------------------------------------------- 
    virtual ~CommandCollection()
    {
        Clear();
    }
    //----------------------------------------------------- 
    /// 从命令列表中移除指定名称的命令
    static Ref<ComplexCommand> RemoveCommand(list_t<Ref<ComplexCommand> >& cmds, const ByteArray& name)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        ByteArray nameArray(name);
        Ref<ComplexCommand> complexCmd;
        for(itr = cmds.begin();itr != cmds.end(); ++itr)
        {
            if(StringConvert::Compare((*itr)->Name(), nameArray, true))
            {
                complexCmd = (*itr);
                cmds.erase(itr);
                break;
            }
        }
        return complexCmd;
    }
    /// 注册命令组
    static size_t RegisteCommand(CommandCollection& collection, const list_t<Ref<ComplexCommand> >& cmdCollection, Ref<ComplexCommand> preCmd, Ref<ComplexCommand> endCmd)
    {
        list_t<Ref<ComplexCommand> >::const_iterator itr;
        size_t count = 0;
        for(itr = cmdCollection.begin();itr != cmdCollection.end(); ++itr)
        {
            ++count;

            Ref<ComplexCommand> complexCmd = collection.Registe((*itr)->Name());
            if(!preCmd.IsNull())
            {
                complexCmd->PrefixBind(preCmd);
            }
            complexCmd->Bind(*itr);
            if(!endCmd.IsNull())
            {
                complexCmd->Bind(endCmd);
            }
        }
        return count;
    }
    /// 注册命令组
    static size_t RegisteCommand(CommandCollection& collection, const list_t<Ref<ComplexCommand> >& cmdCollection)
    {
        list_t<Ref<ComplexCommand> >::const_iterator itr;
        size_t count = 0;
        for(itr = cmdCollection.begin();itr != cmdCollection.end(); ++itr)
        {
            ++count;

            Ref<ComplexCommand> complexCmd = collection.LookUp((*itr)->Name());
            if(complexCmd.IsNull())
            {
                collection._cmd_collection.push_back(*itr);
            }
            else
            {
                complexCmd->Bind(*itr);
            }
        }
        return count;
    }
    /// 注册命令组,如果已经包含命令则不注册
    static size_t UniqueRegisteCommand(CommandCollection& collection, const list_t<Ref<ComplexCommand> >& cmdCollection, Ref<ICommand> preCmd, Ref<ICommand> endCmd)
    {
        list_t<Ref<ComplexCommand> >::const_iterator itr;
        size_t count = 0;
        for(itr = cmdCollection.begin();itr != cmdCollection.end(); ++itr)
        {
            Ref<ComplexCommand> complexCmd = collection.LookUp((*itr)->Name());
            if(!complexCmd.IsNull())
                continue;

            ++count;
            complexCmd = collection._NewCommand((*itr)->Name());
            if(!preCmd.IsNull())
            {
                complexCmd->PrefixBind(preCmd);
            }
            complexCmd->Bind(*itr);
            if(!endCmd.IsNull())
            {
                complexCmd->Bind(endCmd);
            }
        }
        return count;
    }
    /// 注册命令组
    static size_t UniqueRegisteCommand(CommandCollection& collection, const list_t<Ref<ComplexCommand> >& cmdCollection)
    {
        list_t<Ref<ComplexCommand> >::const_iterator itr;
        size_t count = 0;
        for(itr = cmdCollection.begin();itr != cmdCollection.end(); ++itr)
        {
            Ref<ComplexCommand> complexCmd = collection.LookUp((*itr)->Name());
            if(!complexCmd.IsNull())
                continue;

            ++count;
            collection._cmd_collection.push_back(*itr);
        }
        return count;
    }
    /// 绑定命令(后置)
    static size_t BindCommand(list_t<Ref<ComplexCommand> >& cmdCollection, Ref<ICommand> cmd, const IStringArguments& bindArg, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        size_t count = 0;
        for(itr = cmdCollection.begin();itr != cmdCollection.end(); ++itr)
        {
            (*itr)->Bind(cmd, bindArg, option);
            ++count;
        }
        return count;
    }
    /// 绑定命令(后置)
    static size_t BindCommand(list_t<Ref<ComplexCommand> >& cmdCollection, Ref<ICommand> cmd, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        size_t count = 0;
        for(itr = cmdCollection.begin();itr != cmdCollection.end(); ++itr)
        {
            (*itr)->Bind(cmd, option);
            ++count;
        }
        return count;
    }
    /// 绑定命令(前置)
    static size_t PrefixBindCommand(list_t<Ref<ComplexCommand> >& cmdCollection, Ref<ICommand> cmd, const IStringArguments& bindArg, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        size_t count = 0;
        for(itr = cmdCollection.begin();itr != cmdCollection.end(); ++itr)
        {
            (*itr)->PrefixBind(cmd, bindArg, option);
            ++count;
        }
        return count;
    }
    /// 绑定命令(前置)
    static size_t PrefixBindCommand(list_t<Ref<ComplexCommand> >& cmdCollection, Ref<ICommand> cmd, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        size_t count = 0;
        for(itr = cmdCollection.begin();itr != cmdCollection.end(); ++itr)
        {
            (*itr)->PrefixBind(cmd, option);
            ++count;
        }
        return count;
    }
    //----------------------------------------------------- 
    /// 获取所有支持的命令
    size_t GetCommand(const ByteArray& cmdName, list_t<Ref<ComplexCommand> >& cmdlist) const
    {
        list_t<ComplexCommand>::const_iterator itr;
        size_t count = 0;
        for(itr = _cmd_collection.begin();itr != _cmd_collection.end(); ++itr)
        {
            if(cmdName.IsEmpty() || StringConvert::Contains(itr->Name(), cmdName, true))
            {
                cmdlist.push_back(*itr);
                ++count;
            }
        }
        return count;
    }
    /// 获取指定名称的命令
    Ref<ComplexCommand> LookUp(const ByteArray& cmdName)
    {
        // 查找现有的命令
        list_t<ComplexCommand>::iterator itr = _Find(cmdName, true);
        Ref<ComplexCommand> complexCmd;
        if(!_IsEof(itr))
        {
            complexCmd = (*itr);
        }
        return complexCmd;
    }
    /// 以新的名称注册一个空的命令
    Ref<ComplexCommand> Registe(const char* cmdName, bool* pIsExist = NULL)
    {
        // 查找现有的命令
        ByteArray name(cmdName);
        Ref<ComplexCommand> cmd = LookUp(name);
        bool isExist = !cmd.IsNull();
        if(pIsExist != NULL)
        {
            (*pIsExist) = isExist;
        }
        if(isExist)
            return cmd;
        return _NewCommand(name);
    }
    /// 注册新的命令
    Ref<ComplexCommand> Registe(Ref<ComplexCommand> cmd, bool* pIsExist = NULL)
    {
        // 查找现有命令
        if(cmd.IsNull())
            return cmd;
        Ref<ComplexCommand> complexCmd = LookUp(cmd->Name());
        if(complexCmd.IsNull())
        {
            list_t<ComplexCommand>::iterator itr = _cmd_collection.push_back(cmd);
            if(pIsExist != NULL)
            {
                (*pIsExist) = false;
            }
            return (*itr);
        }

        if(pIsExist != NULL)
        {
            (*pIsExist) = true;
        }
        complexCmd->Bind(cmd);
        return complexCmd;
    }
    /// 当命令不存在时注册
    Ref<ComplexCommand> UniqueRegiste(Ref<ComplexCommand> cmd, bool* pIsExist = NULL)
    {
        if(pIsExist != NULL)
        {
            (*pIsExist) = false;
        }
        // 查找现有命令
        if(cmd.IsNull())
            return cmd;
        Ref<ComplexCommand> complexCmd = LookUp(cmd->Name());
        if(!complexCmd.IsNull())
            return complexCmd;

        list_t<ComplexCommand>::iterator itr = _cmd_collection.push_back(cmd);
        if(pIsExist != NULL)
        {
            (*pIsExist) = true;
        }
        itr->Bind(cmd);
        return (*itr);
    }
    /// 解注册命令
    bool Unregiste(const ByteArray& cmdName)
    {
        list_t<ComplexCommand>::iterator itr = _Find(cmdName, true);
        bool isContains = !_IsEof(itr);
        if(isContains)
        {
            _cmd_collection.erase(itr);
        }
        return isContains;
    }
    /// 解注册命令
    Ref<ComplexCommand> Unregiste(const ByteArray& cmdName, CommandCollection& collection)
    {
        list_t<ComplexCommand>::iterator itr = _Find(cmdName, true);
        Ref<ComplexCommand> complexCmd;
        bool isContains = !_IsEof(itr);
        if(isContains)
        {
            complexCmd = (*itr);
            itr = _cmd_collection.snip(itr);
            collection._cmd_collection.splice(itr);
        }
        return complexCmd;
    }
    /// 返回已经注册的命令数
    inline size_t Count() const
    {
        return _cmd_collection.size();
    }
    /// 清空命令集合
    inline void Clear()
    {
        _cmd_collection.clear();
    }
    //----------------------------------------------------- 
    /// 输出注册的命令树
    LOGGER(void Print(LoggerAdapter& _log)
    {
        list_t<ComplexCommand>::iterator itr;
        itr = _cmd_collection.begin();
        if(itr != _cmd_collection.end())
        {
            itr->Print(_log, 0);
            ++itr;
        }
        for(;itr != _cmd_collection.end(); ++itr)
        {
            _log.WriteLine();
            itr->Print(_log, 0);
        }
    })
    //----------------------------------------------------- 
};
//--------------------------------------------------------- 
/// 命令驱动接口
struct ICommandDriver
{
    /// 执行命令
    virtual bool TransmitCommand(const ByteArray& sCmd, const ByteArray& arg, ByteBuilder& rlt) = 0;
};
//--------------------------------------------------------- 
/// 命令驱动辅助类
class CommandHelper 
{
protected:
    //----------------------------------------------------- 
    CommandHelper() {}
    //----------------------------------------------------- 
public:
    //----------------------------------------------------- 
    /// 从参数中反射接口
    template<typename T>
    static Ref<T> InterfaceRef(ICommandHandler::Arguments& arg, const char* key)
    {
        Ref<T> refnull;
        string sRef;
        if(!arg[_strput(key)].Get<string>(sRef))
            return refnull;

        Ref<T>* pRef = reinterpret_cast<Ref<T>*> (ArgConvert::FromString<pointer>(sRef));
        if(pRef == NULL)
            return refnull;

        return (*pRef);
    }
    /// 从类中反射接口
    template<typename T>
    static Ref<T> InterfaceRef(CommandCollection& collection, const char* key)
    {
        // 查找命令
        string refKey = "Ref_";
        refKey += _strput(key);

        Ref<ComplexCommand> complexCmd = collection.LookUp(refKey.c_str());
        if(complexCmd.IsNull())
            return Ref<T>();

        StringArguments arg;
        StringArguments rlt;

        if(!complexCmd->OnCommand(arg, rlt))
            return Ref<T>();
        return InterfaceRef<T>(arg, key);
    }
    //----------------------------------------------------- 
};
//--------------------------------------------------------- 
/// 通过参数反射接口
#define CommandReflectArg(T, arg) CommandHelper::InterfaceRef<T>(arg, #T)
/// 通过类名反射接口
#define CommandReflect(T, collection) CommandHelper::InterfaceRef<T>(collection, #T)
//--------------------------------------------------------- 
/// 基于命令方式的驱动
template<class TArgParser>
class CommandDriver :
    public DeviceBehavior,
    public CommandCollection,
    public ICommandDriver
{
public:
    //----------------------------------------------------- 
    /// 参数转换器类型
    typedef TArgParser ArgParserType;
    //----------------------------------------------------- 
    /// 生成需要绑定的命令参数
    static string Arg(const string& key, const string& val)
    {
        TArgParser parser;
        StringArguments arg;
        arg.Put(key, val);

        ByteBuilder msg(8);
        parser.ToString(arg, msg);

        return msg.GetString();
    }
    /// 生成需要绑定的命令参数
    template<class T>
    static string Arg(const string& key, const T& val)
    {
        string sVal = ArgConvert::ToString<T>(val);
        return Arg(key, sVal);
    }
    //----------------------------------------------------- 
public:
    //----------------------------------------------------- 
    CommandDriver()
    {
        IsRunUniqueCMD = false;
    }
    virtual ~CommandDriver()
    {
        Clear();
    }
    //----------------------------------------------------- 
    /**
     * @brief 枚举所有支持的命令
     * @date 2016-05-07 11:11
     * 
     * @retval CMD : string
     */
    LC_CMD_METHOD(EnumCommand)
    {
        list_t<ComplexCommand>::iterator itr;
        for(itr = _cmd_collection.begin();itr != _cmd_collection.end(); ++itr)
        {
            rlt.Put("CMD", (*itr).Name());
        }
        return true;
    }
    /**
     * @brief 执行指定的命令
     * @date 2016-05-07 12:14
     * 
     * @param [in] CMD : string 命令
     * @param [in] ARG : string 参数
     * 
     * @retval RLT : string 结果
     */
    LC_CMD_METHOD(OnCommand)
    {
        string cmd = arg["CMD"].To<string>();
        string send = arg["ARG"].To<string>();
        ByteBuilder recv(32);
        bool bRet = bRet = TransmitCommand(cmd.c_str(), send.c_str(), recv);
        if(bRet) rlt.Put("RLT", recv.GetString());
        return bRet;
    }
    /**
     * @brief 获取上次错误码和错误信息
     * @date 2016-05-07 13:39
     * 
     * @retval CODE : int 错误码
     * @retval MSG : string 错误信息
     */
    LC_CMD_METHOD(LastError)
    {
        rlt.Put("CODE", ArgConvert::ToString<int>(GetLastErr()));
        rlt.Put("MSG", GetErrMessage());
        ResetErr();
        return true;
    }
    /// 重置错误信息
    LC_CMD_METHOD(ResetError)
    {
        ResetErr();
        return true;
    }
    /// 设置错误码和错误信息
    LC_CMD_METHOD(SetLastError)
    {
        string sCode;
        if(!arg.Get("CODE", sCode))
            return false;

        ResetErr();
        _lasterr = ArgConvert::FromString<int>(sCode);
        _errinfo = arg["MSG"].To<string>();
        return true;
    }
    //----------------------------------------------------- 
    /// 是否执行相同名称的命令
    bool IsRunUniqueCMD;
    /// 处理命令
    bool TransmitCommand(const ByteArray& sCmd, const ByteArray& send = "")
    {
        ByteBuilder recv(32);
        return TransmitCommand(sCmd, send, recv);
    }
    /// 消息分发函数
    virtual bool TransmitCommand(const ByteArray& sCmd, const ByteArray& send, ByteBuilder& recv)
    {
        LOG_FUNC_NAME();
        LOGGER(ByteBuilder callName = sCmd;
        _log << "Call Command:<" << callName.GetString();
        callName = send;
        if(!callName.IsEmpty()) _log << " : " << callName.GetString();
        _log << ">\n");
        // 查找命令表
        list_t<ComplexCommand>::iterator itr;
        TArgParser parser;
        StringArguments arg;
        StringArguments rlt;
        parser.Parse(send, arg);

        bool bHasHandled = false;
        LOGGER(size_t index = 0);
        for(itr = _cmd_collection.begin();itr != _cmd_collection.end(); ++itr)
        {
            LOGGER(++index);
            // 命令注册时,不会注册相同名称的命令,只执行第一个
            ByteArray cmdName(itr->Name());
            if(StringConvert::Compare(cmdName, sCmd, true))
            {
                LOGGER(_log << "Run Command At:[" << index << "]\n");
                if(!itr->OnCommand(arg, rlt))
                {
                    return _logRetValue(false);
                }
                bHasHandled = true;

                if(!IsRunUniqueCMD)
                    break;
            }
        }
        ASSERT_FuncErrInfoRet(bHasHandled, DeviceError::ArgErr, "命令未注册");

        size_t lastLen = recv.GetLength();
        parser.ToString(rlt, recv);
        LOGGER(_log << "RLT:<" << (recv.GetString() + lastLen) << ">\n");
        return _logRetValue(true);
    }
    //----------------------------------------------------- 
};
//--------------------------------------------------------- 
} // namespace driver
} // namespace application 
} // namespace zhou_yb
//--------------------------------------------------------- 
#endif // _LIBZHOUYB_COMMANDDRIVER_H_
//========================================================= 
